﻿using System;
using System.IO;

namespace Rites
{
    public static class Constants
    {
        public const string BOM = "~~~"; //Beginning of message
        public const string EOM = "^^^"; //End of message
        public const int PORT = 12324;
        public const int READBUFFERSIZE = 256; //Used for network comms
        public const int KEYBOARD_BUFFERSIZE = 256; //Keyboard input
    }

    public enum eGameState
    {
        Quitting = 0,
        Offline = 1,
        Lobby = 2,
        GettingIP = 3
    }

    public static class Util
    {
        public static void Log(string logString)
        {
            try
            {
                System.IO.StreamWriter sw = System.IO.File.AppendText("RitesClientLog.txt");
                sw.WriteLine(System.DateTime.Now.ToString() + " -- " + logString);
                sw.Flush();
                sw.Close();
            }
            catch (Exception ex)
            {
                // This is PROBABLY a file acccess contention error because the server is multithreaded
                // Many events which log to this file asynchronously
                // Probably...
                
                //TODO: This should be handled somehow?
            }
        }

        public static MemoryStream CreateMessage(Rites.Networking.RitesProtocol messageType, string paramString, out long messageID, long replyID)
        {
            Util.Log("CreateMessage: " + Enum.GetName(typeof(Rites.Networking.RitesProtocol), messageType) + " (" + paramString + ")");

            MemoryStream msgStream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(msgStream);
            msgStream.Position = 0;

            //Are we replying to a specific request?
            if (replyID > 0)
                messageID = replyID;
            else
                messageID = DateTime.Now.Ticks;

            writer.Write(Constants.BOM + (byte)messageType + "~" + messageID + "~" + paramString + Constants.EOM);
            return msgStream;
        }
    }
}
